﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using llAma.Backend.Interface;
using llAma;

namespace llamaServer
{
    public class ConnectionFactory
    {
        TcpListener mListener;
        public ConnectionFactory()
        {
            int port = Server.Config["listener"]["port"];
            IPAddress address;
            bool modified = false;
            if (port <= 0)
            {
                port = Server.Config["listener"]["port"] = 3900;
                modified = true;
            }
            if (!IPAddress.TryParse(Server.Config["listener"]["address"], out address))
            {
                Server.Config["listener"]["address"] = (address = IPAddress.Any).ToString();
                modified = true;
            }
            int backlog = Server.Config["listener"]["backlog"];
            if (backlog <= 0)
            {
                backlog = Server.Config["listener"]["backlog"] = 40;
                modified = true;
            }
            if (modified)
                Server.SaveConfig();
            mListener = new TcpListener(new IPEndPoint(address, port));
            IBackend b = Backend.Implementation; //Force any constructors to load first
            //Before we start listening. (Static constructors are only called when the class is first accessed.)
            mListener.Start(40);
            mListener.BeginAcceptTcpClient(endAccept, this);
        }
        public event EventHandler NewClientConnected;
        //Dictionary<string, Connection> clients = new Dictionary<string, Connection>();
        private void endAccept(IAsyncResult ar)
        {
            mListener.BeginAcceptTcpClient(endAccept, this);
            try
            {
                TcpClient t = mListener.EndAcceptTcpClient(ar);
                Connection c = new Connection(t);
                NewClientConnected(c, new EventArgs());
            }
            catch
            {

            }

        }

        public void Shutdown()
        {
            try
            {
                mListener.Stop();
            }
            catch { }
        }
    }
}
